//
//  QZMessageDetailVC.m
//  RYJ
//
//  Created by BB on 2017/9/25.
//  Copyright © 2017年 RongKe. All rights reserved.
//

#import "QZMessageDetailVC.h"
#import "WebViewCell.h"
#import "AppHeader.h"

@interface QZMessageDetailVC () {
    BOOL isDocx;
}

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation QZMessageDetailVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.webView.scalesPageToFit =YES;
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (!isStringEmpty(self.webViewURL)) {
        [self requestWebView:self.webViewURL];
    }
    if (!isStringEmpty(self.htmlStr)) {
        [self loadHTMLString:_htmlStr];
    }
    if (!isStringEmpty(self.documentURL)) {
        [self loadHTTPWeb:self.documentURL];
    }
}


- (void)loadHTMLString:(NSString *)htmlString {
    [AppToast showStatusWithString:nil];
    
    NSString *html  = [NSString stringWithFormat:@"<html><style>img {max-width:100%%;}</style><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><meta name=\"MobileOptimized\" content=\"304\"><body><div id=\"viewport\"; name=\"viewport\">%@</div></body></html>", htmlString];
    
    [self.webView loadHTMLString:[QZMessageDetailVC htmlSpecialChars:html] baseURL:nil];
}

- (void)requestWebView:(NSString *)URLString {
    [AppToast showStatusWithString:nil];
    if (![URLString hasPrefix:@"http"]) {
        URLString =[NSString stringWithFormat:@"http://%@", URLString];
    }
    NSString *encodedString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *URL  = [NSURL URLWithString:encodedString];
    
    NSURLRequest *request =[NSURLRequest requestWithURL:URL];
    [self.webView loadRequest:request];
}

- (void)loadHTTPWeb:(NSString*)URLString {
    URLString =[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self downloadFileWithUrl:URLString];
}


//去除HTML标签对
+ (NSString *)trimmedStringWithSpecialString:(NSString*)string {
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n|\r" options:0 error:nil];
    
    NSString *trimmedString =[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];//替换所有html和换行匹配元素为"-"
    return trimmedString;
}
/**
 *  html字符串替换
 *
 *  @param string html源代码
 *
 *  @return 新的html
 */
+ (NSString *)htmlSpecialChars:(NSString*)string {
    NSString * html =string;
    if (isStringEmpty(html)) {
        return @"";
    }
    html =[html stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    html = [html stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    html = [html stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"&amp;nbsp;" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"&amp;ldquo;" withString:@"“"];
    html = [html stringByReplacingOccurrencesOfString:@"&amp;rdquo;" withString:@"”"];
    html = [html stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return html;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [AppToast dismiss];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [AppToast dismiss];
    [AppToast showFileWithString:@"加载失败啦, 请稍后再试"];
}


/**
 *  下载
 *
 *  @param urlStr 下载路径
 */
-(void)downloadFileWithUrl:(NSString*)urlStr {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    // 文件名称
    NSURL *URL = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSString *fileName =[[urlStr componentsSeparatedByString:@"/"] lastObject];
    
    // 保证该文件夹存在(文件的上层文件夹)
    NSString *path =[NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@", DefaultFileName]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //*
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // 告诉AFNetworking缓存到此处(连后缀名)
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", DefaultFileName, fileName]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error) {
            NSString *errorFilePath =[NSString stringWithFormat:@"%@/%@", path, fileName];
            if ([[NSFileManager defaultManager] fileExistsAtPath:errorFilePath]) {
                [[NSFileManager defaultManager] removeItemAtPath:errorFilePath error:nil];
            }
        } else {
            if ([filePath.absoluteString hasSuffix:@".rar"]) {
                [AppToast showFileWithString:@"无法打开.rar文件"];
                return;
            }
            isDocx =[filePath.absoluteString hasSuffix:@".docx"]?YES:NO;
            if (isDocx) {
                if (IS_IPHONE_X) {
                    self.webView_top.constant =-64;
                } else {
                    self.webView_top.constant =-44;
                }
                self.webView_left.constant =-KScreenWidth*0.15;
            }
            [self.webView loadRequest:[NSURLRequest requestWithURL:filePath]];
        }
    }];
    [downloadTask resume];
    // */
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
